package com.example.jdt_xiazai.fragment;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.jdt_xiazai.CircleProgressBar;
import com.example.jdt_xiazai.DownloadMsg;
import com.example.jdt_xiazai.R;
import com.example.jdt_xiazai.base.BaseFragment;
import com.example.jdt_xiazai.base.BasePresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.cpb)
    CircleProgressBar cpb;
    @BindView(R.id.xiazai)
    Button xiazai;
    private String downloadUrl = "https://alissl.ucdl.pp.uc.cn/fs08/2019/07/05/1/110_17e4089aa3a4b819b08069681a9de74b.apk";
    private File file;

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int getLayout() {
        return R.layout.download;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMsg(DownloadMsg downloadMsg) {
        switch (downloadMsg.getCode()) {
            case 0:
                Toast.makeText(getContext(), "下载失败", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                //cpb.setMax(downloadMsg.getMax());
                break;
            case 2:
                cpb.setProgress(downloadMsg.getProgress());
                break;
            case 3:
                Toast.makeText(getContext(), "下载完成", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.xiazai:
                xiazai();
                break;
        }
    }
        private void xiazai () {

            file = new File("/storage/emulated/legacy/a.apk");
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            OkHttpClient okHttpClient = new OkHttpClient();

            final Request request = new Request.Builder()
                    .get()
                    .url(downloadUrl).build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    EventBus.getDefault().post(new DownloadMsg(0, 0, 0));//设置下载失败
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    long max = response.body().contentLength();
                    InputStream is = response.body().byteStream();
                    downloadFile(is, file, max);
                }
            });


        }

        private void downloadFile (InputStream is, File file,long max) throws IOException {
            EventBus.getDefault().post(new DownloadMsg(1, 0, (int) max));
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(file);
                int length = 0;
                byte[] bytes = new byte[1024];
                int com = 0;
                while ((length = is.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                    Log.i("TAG", "downloadFile: " + fileOutputStream.toString());
                    com += length;
                   // cpb.setProgress(com);
                    EventBus.getDefault().post(new DownloadMsg(2, com, (int) max));
                }
                EventBus.getDefault().post(new DownloadMsg(3, com, (int) max));
            } catch (Exception e) {

            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();

                    }
                } catch (IOException e) {

                }
            }
        }

}
